import React, { Component } from 'react';
import { Breadcrumb, Empty, Spin, message } from 'antd';
import _ from 'lodash';
import { withRouter, Link } from 'react-router-dom';
import ComponentCard from './components/component-card';
import BaseInfoCard from './components/base-info-card';
import PageInfoCard from './components/page-info-card';
import PortsCard from './components/port-card';
import EmptyDataImg from '@images/empty-data-blue.png';
import { getZoomeyeOrgAssetDetail, setZoomeyeOrgAssetVerify } from '@api/zoomeyeOrgAsset';
import './index.less';

const prefixCls = 'public-query-detail';

const COMPONENT_NAME_MAP = {
  component: '组件',
  db: '数据库',
  framework: '框架',
  server: 'Web 容器',
  system: '操作系统',
  webapp: 'Web 应用',
  waf: 'Web 防火墙'
};

class PubliceQueryDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isExistAssetList: false,
      loading: true
    };
    // eslint-disable-next-line
    this.id = props.match.params.id;
  }

  componentDidMount() {
    this.getDetails();
  }

  getDetails = () => {
    this.setState({ loading: true });
    getZoomeyeOrgAssetDetail({ id: this.id })
      .then(res => {
        const baseInfoData = _.get(res, 'data.data.assetInfo', {});
        const webParams = _.get(res, 'data.data.assetInfo.webParams', {});
        const ip = _.get(res, 'data.data.assetInfo.ip[0]', '');
        const portInfo = _.get(res, 'data.data.portInfo', []);

        const portsData = portInfo[ip] || [];
        const isHost = _.get(baseInfoData, 'type') === 'host';
        const isVerified = _.get(baseInfoData, 'isVerified', false);
        const componentData = !isHost ? this.createComponentData(webParams) : [];
        const pageInfoData = !isHost
          ? _.get(webParams, 'header', '') + _.get(webParams, 'rawData', '')
          : '';

        this.setState({
          baseInfoData,
          portsData,
          componentData,
          pageInfoData,
          isExistAssetList: isVerified,
          isHost,
          loading: false
        });
      })
      .catch(() => {
        message.error('资产详情获取失败！');
        this.setState({ loading: false });
      });
  };

  createComponentData(webParams) {
    if (_.isEmpty(webParams)) {
      return [];
    }
    const filterWebParams = _.pickBy(webParams, _.isArray);
    return _.reduce(
      filterWebParams,
      (res, v, key) => {
        const data = v.map(i => {
          return {
            classification: COMPONENT_NAME_MAP[key],
            ...i
          };
        });
        res.push(...data);
        return res;
      },
      []
    );
  }

  addOrUpdateToAsset = () => {
    const { isExistAssetList } = this.state;
    const body = {
      ids: [this.id]
    };
    const msg = isExistAssetList ? '更新' : '添加';

    setZoomeyeOrgAssetVerify(body)
      .then(() => {
        this.getDetails();
        message.success(`${msg}成功`);
      })
      .catch(() => {
        message.error(`${msg}失败`);
      });
  };

  render() {
    const {
      baseInfoData,
      portsData,
      componentData,
      pageInfoData,
      isExistAssetList,
      isHost,
      loading
    } = this.state;
    const isEmpty = _.isEmpty(componentData) && _.isEmpty(pageInfoData) && _.isEmpty(portsData);

    return (
      <div className={`${prefixCls}`}>
        <Spin spinning={loading} tip="加载中...">
          <div className={`${prefixCls}-bread`}>
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/asset-config/asset-org-manage">公网资产查询</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                <span className={`${prefixCls}-title`}>资产详情</span>
              </Breadcrumb.Item>
            </Breadcrumb>
          </div>
          <div className={`${prefixCls}-header`}>
            <BaseInfoCard
              data={baseInfoData}
              isHost={isHost}
              onChange={this.addOrUpdateToAsset}
              isExistAssetList={isExistAssetList}
            />
          </div>
          <div className={`${prefixCls}-body`}>
            <div className={`${prefixCls}-title`}>端口&nbsp;/&nbsp;服务</div>
            <div className={`${prefixCls}-body-line`} />
            {!_.isEmpty(componentData) ? <ComponentCard data={componentData} /> : ''}
            {!_.isEmpty(pageInfoData) ? <PageInfoCard data={pageInfoData} /> : ''}
            {!_.isEmpty(portsData) ? <PortsCard data={portsData} /> : ''}
            {isEmpty && (
              <Empty
                image={EmptyDataImg}
                imageStyle={{
                  margin: '120px 0 24px',
                  height: 296
                }}
                description={
                  <div>
                    <span style={{ color: '#2A2B30' }}>端口/服务暂无数据</span>
                  </div>
                }
              />
            )}
          </div>
        </Spin>
      </div>
    );
  }
}

export default withRouter(PubliceQueryDetail);
